var dgEditIndex=new Array();
function dgLoadSuccess(data){
	if(data.total==0){
		$.messager.alert('提示', "暂无记录!",'info');
	}
}
function initDatagridAdmin(cf,url,btnAdd,btnDel,btnModify,btnBase,btnOut,noPage){  //调用外部的工具栏#tb时可省掉后面的四个参数
	dgEditIndex[cf]=-1;
	var btnArr=[];
	if(btnAdd==1){btnArr.push({text:'增加',iconCls:'icon-add',handler:function(){add(cf)}},'-')}
	if(btnDel==1){btnArr.push({text:'删除',iconCls:'icon-remove',handler:function(){del(cf, url)}},'-')};
	if(btnModify==1){btnArr.push({text:'修改',iconCls:'icon-edit',handler:function(){modify(cf)}},'-')};
	if(btnBase==1) {
		btnArr.push({text:'保存',iconCls:'icon-save',handler:function(){save(cf)}},'-');
		btnArr.push({text:'取消',iconCls:'icon-undo',handler:function(){undo(cf)}});	
	}
	if(btnOut==1){btnArr.push('-',{text:'导出为EXCEL',iconCls:'icon-save',handler:function(){outExcel(cf, url)}})};
	$("#"+cf+"dg").datagrid({
		url: url + "/pageQuery",
		rownumbers: true,
		striped: true,
		border: false,
		pagination: noPage ? false : true,
		pageSize: 30,
		fitColumns: true,
		autoRowHeight: false,
		singleSelect: true,
		fit: true,
		toolbar: btnArr,
	    onAfterEdit: function(rowIndex,rowData,changes){
	    	if($.isEmptyObject(changes)) {
	    		var dgObj=$('#'+cf+'dg');
				dgObj.datagrid('rejectChanges');
				dgEditIndex[cf]=-1;
				return;	
			}
			changes.id = rowData.id;
	    	addmodify(changes, cf, url)
	    },
		onLoadSuccess: function(data){
	        $(".note").tooltip({
		        onShow: function () {
			        $(this).tooltip('tip').css({
			       		borderColor: '#000'
			        });
		        }
	        });
		}
	})
	var tb = $("#"+cf+"tb").html();
	if(tb) {
		$(".datagrid-toolbar").prepend(tb);
		$("#"+cf+"tb").remove();
	}
}
function initDatagrid(cf, url){
	dgEditIndex[cf]=-1;
	$("#"+cf+"dg").datagrid({
		url: url + "/pageQuery",
		rownumbers:true,
		striped:true,
		border:false,
		pagination:true,
		pageSize:30,
		fitColumns:true,
		singleSelect: true,
		fit: true,
		toolbar: '#'+cf+'tb',
		onLoadSuccess: function(data){
	        $(".note").tooltip({
		        onShow: function () {
			        $(this).tooltip('tip').css({
			       		borderColor: '#000'
			        });
		        }
	        });
		},
		onAfterEdit: function(rowIndex,rowData,changes){
	    	if($.isEmptyObject(changes)) {
	    		var dgObj=$('#'+cf+'dg');
				dgObj.datagrid('rejectChanges');
				dgEditIndex[cf]=-1;
				return;	
			}
			changes.ID = rowData.ID;
	    	addmodify(changes, cf, url)
	    }
	})
}
function add(cf){
	var dgObj=$('#'+cf+'dg');
	if(dgEditIndex[cf]==-1){	
		dgObj.datagrid('insertRow',{index:0,row:{}});
		dgObj.datagrid('beginEdit',0);
		dgEditIndex[cf]=0;
	}else{
		$.messager.alert('提示','请先保存或取消编辑！','info');
	}
}
function modify(cf){
	if(dgEditIndex[cf]>-1){
		$.messager.alert('提示','请先保存或取消编辑！','info');
	}else{
		var dgObj=$('#'+cf+'dg');
		var rows=dgObj.datagrid('getSelections');
		if(rows.length==1){			
			var cIndex=dgObj.datagrid('getRowIndex',rows[0]);	
			dgObj.datagrid('beginEdit',cIndex);
			dgEditIndex[cf]=cIndex;
		}else{
			$.messager.alert('提示','请选择一行编辑！','info');	
		}
	}
}
function del(cf, url){
	if(dgEditIndex[cf]>-1){
		$.messager.alert('提示','请先保存或取消编辑！','info');
	}else{
		var dgObj=$('#'+cf+'dg');
		var rows=dgObj.datagrid('getSelections');
		if(rows.length>0){
			$.messager.confirm("请确认","你确定要删除已选择的记录吗？",function(b){
				if(b){
					var delIds=[];
					for(var i=0;i<rows.length;i++){
						delIds.push(rows[i].id);
					}
					$.ajax({
					   type:"POST",
					   url: url + "/del",
					   data:{delIds:delIds.join(",")},
					   success: function(r){
					   		if(r.code == '000') {
					   			$.messager.alert('提示', "删除成功!",'info');
					   			dgObj.datagrid('reload');
					   			return;
					   		}
						    $.messager.alert('提示', "失败",'error');
						    undo(cf);
					    }
					});
				}
			})
		}else{
			$.messager.alert('提示','请选择要删除的行！','error');
		}
	}
}
function save(cf){
	$('#'+cf+'dg').datagrid('endEdit',dgEditIndex[cf]);
}
function undo(cf){
	$('#'+cf+'dg').datagrid('rejectChanges');
	dgEditIndex[cf]=-1;
}
function reload(cf) {
	$('#'+cf+'dg').datagrid('reload');
	dgEditIndex[cf]=-1;
}
function resetForm(cf){
	$('#' + cf + "Form")[0].reset();
}
function searchForm(cf) {
	var dataGrid = $('#'+cf+'dg');
	dataGrid.datagrid('load', $.serializeObject($('#' + cf + "Form")));
}
function addmodify(changes, cf, url){
	var dgObj=$('#'+cf+'dg');
	$.ajax({
	   type: "POST",
	   url: url + "/addUpdate",
	   data: changes
	}).done(function(data) {
	   	if(data.code == '000') {
	   	 	dgEditIndex[cf]=-1;
	   	 	$.messager.alert('提示', "提交成功!",'info');
			dgObj.datagrid('reload');
			return;
	   	}
	   	undo(cf);
	   	$.messager.alert('错误',"提交失败",'error');			
	}).fail(function(resp) {
		$.messager.alert('错误',"提交失败",'error');		
	});
}

function outExcel(cf, url){
	window.location.href = url+"/exportExcel.html?" + $('#'+cf+'Form').serialize();
}
//扩展datagrid的editors方法
$.extend($.fn.datagrid.methods,{
	addEditor:function(jq,param){
		if(param instanceof Array){
			$.each(param,function(index,item){
				var e=$(jq).datagrid('getColumnOption',item.field);
				e.editor=item.editor;
			});
		}else{
			var e=$(jq).datagrid('getColumnOption',param.field);
			e.editor=param.editor;
		}
	},
	removeEditor:function(jq,param){
		if(param instanceof Array){
			$.each(param,function(index,item){
				var e=$(jq).datagrid('getColumnOption',item);
				e.editor={};
			});
		}else{
			var e=$(jq).datagrid('getColumnOption',param);
			e.editor={};
		}
	}
});

function upfile(cf){
	$('#'+cf+'formfile').form('submit',{success:function(data){$.messager.alert('提示',data);}});  
}
function piliangdaoruing(cf){
	var url=cf+".asp?ac=callPiliangdaoru";
	$.get(url,function(data){
		if(isNaN(data)){
			$.messager.alert('提示',data,'error');	
		}else if(data<0){
			$.messager.alert('提示',"导入失败")
		}else{
			$.messager.alert('提示','共导入'+data+'条记录');
			$('#'+cf+'dg').datagrid('reload');
		}
	});
	
}

function exportExcel(searchForm,exportUrl) {
	$("#" + searchForm + "Form").attr('action',exportUrl);
	$("#" + searchForm + "Form").submit();  
}

/**
 * 
 * @requires jQuery
 * 
 * 将form表单元素的值序列化成对象
 * 
 * @returns object
 */
$.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (o[this['name']]) {
			o[this['name']] = o[this['name']] + "," + this['value'];
		} else {
			o[this['name']] = this['value'];
		}
	});
	return o;
};